import { ref, reactive } from 'vue'
import { logout, updatepassword } from "~/api/manager";
import { toast, showModal } from "~/composables/util";
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'



export   function useRepassword() {

    
const router = useRouter()
const store = useStore()

    //修改密码

    const formDrawerRef = ref(null)
    // do not use same name with ref
    const form = reactive({
        oldpassword: "",
        password: "",
        repassword: ""

    })

    const rules = {
        oldpassword: [
            { required: true, message: '请输入原密码', trigger: 'blur' }

        ],
        password: [
            { required: true, message: '请输入新密码', trigger: 'blur' }

        ],
        repassword: [
            { required: true, message: '请确认新密码', trigger: 'blur' }

        ]

    }
    const formRef = ref(null)
    //避免多次点击 
    const onSubmit = () => {
        formRef.value.validate((valid) => {
            if (!valid) {
                return false
            }
            formDrawerRef.value.showLoading()
            updatepassword(form)
                .then(res => {
                    toast("修改密码成功,请重新登录")
                    store.dispatch("logout")
                    //跳转到登录页
                    router.push("/login")
                })
                .finally(() => {
                    formDrawerRef.value.hideLoading()
                })


        })

    }
    const openRePasswordForm = ()=>formDrawerRef.value.open()
    return {
        formDrawerRef,
        form,
        rules,
        formRef,
        onSubmit, 
        openRePasswordForm

    }
}

export  function useLogout(){
    const router = useRouter()
const store = useStore()
    function handlelogout() {
        showModal("是否要退出登录？").then(res => {
            logout()
                .finally(() => {
                    store.dispatch("logout")
    
                    //跳转到登录页
                    router.push("/login")
                    //提示退出登录成功
                    toast("退成登录成功")
                })
        })
    }
    return {
        handlelogout
    }
}
